package logic

import (
	"context"
	"errors"
	"fmt"
	"house-info-net/models/cache"
	"house-info-net/models/mysql"
	"time"

	"house-info-net/houserpc/houserpc"
	"house-info-net/houserpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type GoodsAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodsAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodsAddLogic {
	return &GoodsAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 商品创建
func (l *GoodsAddLogic) GoodsAdd(in *houserpc.GoodsAddRequest) (*houserpc.GoodsAddResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	if err := user.FindUserByUserId(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("用户不存在")
	}
	goods := mysql.Goods{
		Title: in.Title,
		Price: float64(in.Price),
		Stock: in.Stock,
	}
	err := goods.GoodsAdd(mysql.DB)
	if err != nil {
		return nil, err
	}
	key := fmt.Sprintf("goodsadd_%d", goods.ID)
	cache.Rdb.Set(l.ctx, key, goods, time.Minute*30)

	return &houserpc.GoodsAddResponse{
		GoodsId: int64(goods.ID),
	}, nil
}
